<?php

/**
 * QuanNDA convert from OanhTTK Helper, using in SGN version using vPortal.
 * @author OanhTTK
 * @version
 */
class SGN_Counter
{
    /**
	 * @var int
	 */
	private $_timeout = '';

	/**
	 * @var int
	 */
	private $_timeOutLargerHour = 0;

	/**
	 * Constructor: initialize plugin loader
	 *
	 * @return void
	 */
	public function __construct($timeout)
	{
		$this->_timeout = $timeout;
		if ($this->_timeout > 3600) {
			$this->_timeOutLargerHour = 1;
		}
	}
	/**
	 * Simplier block calculation
	 * 
	 * @param integer $timeout
	 * @return integer
	 */
    public static function getBlock($timeout)
    {
        $counter = new self($timeout);
        return $counter->calculateBlock();
    }
	/**
	 * increase counter
	 * @param $key
	 * @return void
	 */
	public function calculateBlock()
	{
		try {
			if (!$this->_timeout) {
				return 0;
			}
			if ($this->_timeOutLargerHour) {
				$this->_blockId = ceil((date('H') * 3600 + date('i') * 60 + date('s')) / $this->_timeout);
				$this->_maxId = ceil((23 * 3600 + date('i') * 60 + date('s')) / $this->_timeout);
			} else {
				$this->_blockId = ceil((date('i') * 60 + date('s')) / $this->_timeout);
				$this->_maxId = ceil((59 * 60 + date('s')) / $this->_timeout);
			}
			return $this->_blockId;
		} catch (Exception $e) {
			throw new Zend_Exception("Zend Counter : " . $e->getMessage());
		}
	}
	/**
	 * 
	 * Get block number based on $pointer
	 * @param integer $pointer
	 * 
	 * return integer
	 */ 
	public function getPosition($pointer = 0) 
	{
	    if (!$this->_maxId) {
	        $this->calculateBlock();
	    }
	    if ($pointer < 0) {
    	    if (abs($pointer) > $this->_maxId) {
    	        $pointer = $this->_maxId + $pointer;
    	    }
	        if ($this->_blockId - abs($pointer) < 0) {
	            return $this->_maxId - abs(abs($pointer) - $this->_blockId) - 1;
	        }
	        return $this->_blockId - abs($pointer);
	    }
	    if ($pointer > 0) {
	        if ($pointer > $this->_maxId) {
    	        $pointer = $pointer - $this->_maxId;
    	    }
	        if ($this->_blockId + $pointer > $this->_maxId) {
	            return abs($this->_blockId + $pointer - $this->_maxId) - 1;
	        }
	        return $this->_blockId + $pointer;
	    }
	}
}